package servlet;

import entity.Owner;
import dao.OwnerDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private OwnerDao ownerDao = new OwnerDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            Owner owner = ownerDao.login(username, password);
            if (owner != null) {
                HttpSession session = request.getSession();
                session.setAttribute("owner", owner);
                response.sendRedirect("index.jsp");
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("error", "登录失败：" + e.getMessage());
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}